﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ideas2Realize.Data.Business.Interface;

namespace Ideas2Realize.Data.Business
{
    public class DeviationRepository 
        : PetaPocoRepository<Models.Deviation>, 
        IDeviationRepository
    {
        private const string DEFAULT_SELECT_QUERY = "select * from deviations";
        private const string DEFAULT_VIEW_SELECT_QUERY = "select * from deviationsview";


        public Models.Deviation GetById(int id)
        {
            return db.Single<Models.Deviation>(id);
        }

        public IEnumerable<Models.Deviation> GetAll()
        {
            var query = Query(DEFAULT_SELECT_QUERY);

            return query;
        }

        public IEnumerable<Models.DeviationsView> GetByUserId(int userId)
        {
            // int dtId = (int)deviationType;

            PetaPoco.Sql sql = PetaPoco.Sql.Builder;

            sql.Append(DEFAULT_VIEW_SELECT_QUERY);

            //if (dtId != (int)DeviationTypeEnum.None)
            //{
            //    sql.Where("DeviationType=@0", dtId);
            //}

            if (userId > 0)
            {
                sql.Where("UserId=@0", userId);
            }

            return db.Fetch<Models.DeviationsView>(sql);
        }

        public PetaPoco.Page<Models.Deviation> GetPaged(int limit, int page)
        {
            return PagedQuery(page, limit, DEFAULT_SELECT_QUERY);
        }

        public PetaPoco.Page<Models.DeviationsView> GetPagedView(int limit, int page, DeviationTypeEnum deviationType, int? userId)
        {
            int dtId = (int)deviationType;

            PetaPoco.Sql sql = PetaPoco.Sql.Builder; 

            sql.Append(DEFAULT_VIEW_SELECT_QUERY);

            if(dtId != (int)DeviationTypeEnum.None) {
                sql.Where("DeviationType=@0",dtId);
            }

            if (userId.HasValue && userId.Value > 0)
            {
                sql.Where("UserId=@0", userId.Value);
            }

            return db.Page<Models.DeviationsView>(page, limit, sql);
        }


        public void BindUser(int[] users, int id)
        {
            foreach (int usr in users)
            {
                Models.UserDeviation obj = new Models.UserDeviation();   
                obj.DeviationId = id;
                obj.UserId = usr;
                obj.OwnerFromDate = DateTime.Now; 
                obj.Insert();
            }
        }
    }
}
